<script setup lang="ts">
import useToast from '@/hooks/useToast';
import HomeRequest from '@/request/homeRequest';
import useAppStore from '@/store/modules/app';
import { requestPayment } from '@/utils/requestPayment';
import to from '@/utils/to';

interface IState {
  beeperId: number;
  info?: IGetPayInfo;
  radio: number;
  number: number;
  months: number;
  price: number;
  activityText?: string;
}

const store = useAppStore();
const state = reactive<IState>({ beeperId: store.$state.beeperId, radio: 1, number: 1, months: 1, price: 0, activityText: '' });
const { showToast } = useToast();

onLoad((options) => {
  if (!options) return;
  fetchPropertyPaymentInfo();
  fetchActivePreferential(1);
});

// 获取楼栋单元层 物业缴费基本信息
const fetchPropertyPaymentInfo = () => {
  HomeRequest.GetPropertyPaymentInfo({ beeperId: state.beeperId, btnId: store.$state.btnInformation!.id, hasLoading: true }).then((res) => {
    state.info = res.data;
    state.info.pmcExpireDate = state.info.pmcExpireDate.substring(0, 10);
    state.info.pmcLatestDate = state.info.pmcLatestDate.substring(0, 10);
    const cycleCollection: number[] = state.info.feePeriod.split(',').map(Number);
    if (cycleCollection.length > 0) {
      if (cycleCollection[0] === 1) handleProcessingPrices(1);
      if (cycleCollection[0] === 2) handleProcessingPrices(3);
      if (cycleCollection[0] === 3) handleProcessingPrices(12);
    }
  });
};

/**
 * 获得产品商户的活动优惠内容即活动价
 */
const fetchActivePreferential = (months: number) => {
  HomeRequest.GetActivePreferential({ beeperId: state.beeperId, btnId: store.$state.btnInformation!.id, months }).then((res) => {
    state.activityText = res.data;
  });
};

// 年月日切换
const handlePaymentCycleChange = (e: any) => {
  let months = 1;
  if (e.detail === 1) months = 1;
  if (e.detail === 2) months = 3;
  if (e.detail === 3) months = 12;
  state.radio = e.detail;
  state.number = 1;
  fetchActivePreferential(months);
  handleProcessingPrices(months);
};

/**
 * 月份数量切换
 * @param e
 */
const handleTextareaInput = (e: any) => {
  const { radio } = state;
  let months = 1;
  if (radio === 1) months = 1 * e.detail;
  if (radio === 2) months = 3 * e.detail;
  if (radio === 3) months = 12 * e.detail;
  state.number = e.detail;
  state.months = months;
  fetchActivePreferential(months);
  handleProcessingPrices(months);
};

/**
 * 处理价格
 */
const handleProcessingPrices = (months: number) => {
  const { houseSpace, pmcPrice, pmcSingleDiscount } = state.info!;
  const price = houseSpace * pmcPrice * months * (pmcSingleDiscount || 1);
  /**
    将 num 乘以 10^decimalPlaces。
    如果保留 2 位小数，乘以 100，将小数部分移到整数位。
    使用 Math.round 进行四舍五入：
    Math.round 是 JavaScript 内置的精确四舍五入方法。
   */
  const factor = Math.pow(10, 2); // 计算 10 的幂 真正意义上的四舍五入
  state.price = Math.round(price * factor) / factor;
};

// 缴费提交
const handlePaymentSubmission = async () => {
  const params = { beeperId: store.$state.beeperId, btnId: store.$state.btnInformation!.id, openId: store.$state.userInfo.openId, months: state.months, amount: state.price };
  const [err, res] = await to(HomeRequest.PropertyPaymentInfoOrder({ ...params, hasLoading: true }));
  if (err) return;
  const [payErr] = await to(requestPayment({ ...res.data, provider: 'wxpay', orderInfo: '' }));
  if (payErr) return;
  showToast('缴费成功', 'success');
};
</script>
<template>
  <view class="c-pd" v-if="state.info">
    <van-cell-group inset>
      <van-cell title="门牌号" :value="state.info.address" />
      <van-cell title="房屋面积" :value="state.info.houseSpace + 'm²'" />
      <van-cell title="上次缴费时间" :value="state.info.pmcLatestDate" />
      <van-cell title="到期时间" :value="state.info.pmcExpireDate" />
    </van-cell-group>
    <view class="my-3">
      <van-cell-group inset>
        <van-cell center title="缴费周期" use-label-slot>
          <view slot="right-icon">
            <van-radio-group :value="state.radio" direction="horizontal" @change="handlePaymentCycleChange">
              <van-radio v-for="(item, index) in state.info.feePeriod.split(',').map(Number)" :name="item" :key="index">{{ item === 1 ? '月' : item === 2 ? '季度' : '年' }}</van-radio>
            </van-radio-group>
          </view>
        </van-cell>
        <van-cell title="数量" use-label-slot>
          <view slot="right-icon">
            <van-stepper :value="state.number" integer input-width="100rpx" @change="handleTextareaInput" />
          </view>
        </van-cell>
        <van-cell title="价格" use-label-slot>
          <view slot="right-icon"> {{ state.info.pmcPrice }} 元 / m² </view>
        </van-cell>
        <van-cell v-if="state.info.pmcSingleDiscount" title="折扣" use-label-slot>
          <view slot="right-icon"> {{ state.info.pmcSingleDiscount * 10 }} 折 </view>
        </van-cell>
      </van-cell-group>
    </view>
    <van-cell-group inset v-if="state.activityText">
      <van-cell title="优惠活动" :label="state.activityText" />
    </van-cell-group>
  </view>
  <van-submit-bar v-if="state.info && state.price" :price="state.price * 100" button-type="primary" button-text="提交订单" @submit="handlePaymentSubmission" />
</template>
